package com.beself.controller;/*
    author:李思远
    adte:2019/10/1314:48
    description:
*/

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.beself.entity.TUser;
import com.beself.service.UserService;
import com.beself.until.RandomStringTLUtils;
import com.beself.until.RestJson;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/api/user")
@SessionAttributes({"UTel","Numeric","uId"})
public class UseController {
    @Resource
    private UserService userService;
    @Resource
    private RestJson restJson;

    //根据手机号查询
    @RequestMapping("/zc/isiphone")
    @ResponseBody
    public RestJson findbyuUsername(String uTel) {
        System.out.println("uTel = " + uTel);
        TUser tUser = userService.findbyuUsername(uTel);
        System.out.println("tUser = " + tUser);
        if (tUser != null) {
            restJson = new RestJson(false, "账号被注册", 1);
            // return "1";//代表注册过了
        }
        restJson = new RestJson(true, "账号未被注册", 0);
        //return "0";//代表没注册
        return restJson;
    }

    //判断验证码是否正确
    @RequestMapping("/yzm/isif")
    @ResponseBody
    public RestJson yanzhegnma(String yanzhengma, @ModelAttribute("Numeric") String numeric, @ModelAttribute("UTel") String uTel, ModelMap map) {
        System.out.println("yanzhengma = " + yanzhengma);
        System.out.println("numeric = " + numeric);
        System.out.println("uTel = " + uTel);

        if (numeric.equals(yanzhengma)) {
            restJson = new RestJson(true, "验证码正确", 0);
            // return "0";//代表正确
        } else {
            restJson = new RestJson(false, "验证码错误", 1);
        }
        //return "1";//代表错误
        return restJson;
    }

    @RequestMapping(value ="/zc/insertxx",method = RequestMethod.POST)
    @ResponseBody
    //@Transactional
    public RestJson insert(String uPassword, @ModelAttribute("UTel") String uTel) {
        System.out.println(11111111);
        System.out.println("uTel = " + uTel);
        System.out.println("uPassword = " + uPassword);

        int i = userService.insertUser(uTel, uPassword);
        System.out.println("i = " + i);
        if (i > 0) {
            TUser tUser = userService.findbyuUsername(uTel);
            System.out.println("新增的id是：" + tUser.getuId());
            //将新增的id插入关联表
            int insertuserid = userService.insertuserid(tUser.getuId());
            System.out.println("insertuserid,controller = " + insertuserid);

            TUser user=new TUser();
            user.setuId(tUser.getuId());

            restJson = new RestJson(true, "注册成功", user);
            //return "1";//代表注册成功
        } else {
            restJson = new RestJson(false, "注册失败", 0);
            // return "0";//代表注册失败
        }
        return restJson;
    }

    //账号密码进行登录
    @RequestMapping(value = "/zc/login", method = RequestMethod.POST)
    @ResponseBody
    public RestJson findbyUser(String uTel, String uPassword,ModelMap map,HttpServletResponse response) {
        System.out.println("uTel = " + uTel);
        TUser tUser1 = userService.findbyuUsername(uTel);//查出来了代表被注册了

        if (tUser1!=null)
        {
            TUser tUser = userService.findbyUser(uTel, uPassword);

            TUser user=new TUser();
            user.setuId(tUser.getuId());

            map.addAttribute("uId",tUser.getuId());
            if (tUser != null) {
                restJson = new RestJson(true, "登陆成功", user);
                // return "0";//代表正确
            } else {
                restJson = new RestJson(false, "登录失败", 1);
            }
            return restJson;
        }else {
            restJson = new RestJson(false, "此账号未注册", 2);
            return restJson;
        }
    }

    @RequestMapping("/xg/mima")
    @ResponseBody
    public RestJson updatemima(@ModelAttribute("UTel") String uTel, String uPassword) {

        System.out.println(11);
        System.out.println(uTel);
        int updatemima = userService.updatemima(uTel, uPassword);
        System.out.println("updatemima = " + updatemima);
        if (updatemima > 0) {
            restJson = new RestJson(true, "修改成功", 1);
            // return "1";//修改成功
        } else {
            restJson = new RestJson(false, "修改失败", 0);
        }
        return restJson;
        // return "0";//修改失败
    }

    @RequestMapping("/loginout")
    public RestJson aa(HttpSession session, SessionStatus sessionStatus, HttpServletResponse response,@ModelAttribute("UTel") String uTel) {

        try {
            System.out.println("取到传过来的值uTel = " + uTel);
            System.out.println("取到注解中的值"+session.getAttribute("UTel"));
            Object obj=session.getAttribute("UTel");
            System.out.println("将注解中的值给了obj = " + obj);
            session.invalidate();
            sessionStatus.setComplete();

            System.out.println("退出成功");
                restJson = new RestJson(true, "退出成功", 1);
        } catch (Exception e) {
            restJson = new RestJson(false, "退出失败", 0);
        }
        return restJson;


    }

    //使用账号密码进行登录
    //注册走的路径
    @RequestMapping("/ajaxNum")
    @ResponseBody
    public RestJson sendMsg(String uTel, HttpSession session, ModelMap map,HttpServletResponse response) throws ClientException
    {//拿到手机号
        System.out.println(uTel);
        System.out.println(11);
        TUser tUser = userService.findbyuUsername(uTel);//查出来了代表被注册了
        System.out.println("tUser = " + tUser);
        map.addAttribute("uTel",uTel);

       /* Cookie cookie=new Cookie("uId",String.valueOf(tUser.getuId()));
        response.addCookie(cookie);*/

        if (tUser != null)
        {
            restJson = new RestJson(false, "账号被注册", 1);//代表被注册了
            return restJson;
        } else {
            System.out.println("哈哈"+111);
            //调用阿里通信接口
            //设置超时时间-可自行调整
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //初始化ascClient需要的几个参数
            final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
            final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
            //替换成你的AK
            final String accessKeyId = "LTAI4FwKVwzLxSs6tdGQ8vkp";//你的accessKeyId,参考本文档步骤2
            final String accessKeySecret = "wjV6rj3g4Z7cbtrIJG27GeWA7RNUmQ";//你的accessKeySecret，参考本文档步骤2
            //初始化ascClient,暂时不支持多region（请勿修改）

            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                    accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            //使用post提交
            request.setMethod(MethodType.POST);
            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
            request.setPhoneNumbers(uTel);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName("吾乃武林至尊");
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode("SMS_175120176");
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
            //生成几位的验证码
            String numeric = RandomStringTLUtils.randomNumeric(4);
            request.setTemplateParam("{\"code\":\"" + numeric + "\"}");
            //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId("qf");
            //请求失败这里会抛ClientException异常
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))
            {
                //请求成功
                //真实应用的时候验证码在服务端有记录
                //客户端由客户来输入
                //客户输入的验证码和服务端做匹配
                System.out.println("numeric = " + numeric);
                //将手机号存入session
                map.addAttribute("UTel", uTel);
                //将验证码存入session
                map.addAttribute("Numeric", numeric);
                restJson = new RestJson(true, "账号未被注册", 0);
                return restJson;
            } else {//发送失败原因
                System.out.println("状态" + sendSmsResponse.getCode());
                System.out.println(sendSmsResponse.getMessage());
                restJson = new RestJson(false, "发送失败", 2);
                return restJson;
            }
        }
    }
    //使用验证码进行登陆
    @RequestMapping("/iPhoneyzm")
    @ResponseBody
    public RestJson shouji(String uTel, HttpSession session, ModelMap map, HttpServletResponse response) throws ClientException
    {//拿到手机号
        System.out.println(11);
        System.out.println("uTel = " + uTel);

        TUser tUser = userService.findbyuUsername(uTel);//查询出来了，有此账号
        System.out.println("tUser = " + tUser);
        if (tUser!=null)
        {
            map.addAttribute("uId",tUser.getuId());


            Cookie cookie=new Cookie("uId",String.valueOf(tUser.getuId()));
            response.addCookie(cookie);
            System.out.println(uTel);
            System.out.println(11);
            //调用阿里通信接口
            //设置超时时间-可自行调整
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //初始化ascClient需要的几个参数
            final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
            final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
            //替换成你的AK
            final String accessKeyId = "LTAI4FwKVwzLxSs6tdGQ8vkp";//你的accessKeyId,参考本文档步骤2
            final String accessKeySecret = "wjV6rj3g4Z7cbtrIJG27GeWA7RNUmQ";//你的accessKeySecret，参考本文档步骤2
            //初始化ascClient,暂时不支持多region（请勿修改）

            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                    accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            //使用post提交
            request.setMethod(MethodType.POST);
            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
            request.setPhoneNumbers(uTel);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName("吾乃武林至尊");
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode("SMS_175120176");
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
            //生成几位的验证码
            String numeric = RandomStringTLUtils.randomNumeric(4);
            request.setTemplateParam("{\"code\":\"" + numeric + "\"}");
            //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId("qf");
            //请求失败这里会抛ClientException异常
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))
            {
                //请求成功
                //真实应用的时候验证码在服务端有记录
                //客户端由客户来输入
                //客户输入的验证码和服务端做匹配
                System.out.println("numeric = " + numeric);
                //将手机号存入session
                map.addAttribute("UTel", uTel);
                //将验证码存入session
                map.addAttribute("Numeric", numeric);
                restJson = new RestJson(true, "发送成功", 0);
                return restJson;
            } else {//发送失败原因
                System.out.println("状态" + sendSmsResponse.getCode());
                System.out.println(sendSmsResponse.getMessage());
                restJson = new RestJson(false, "发送失败", 1);
                return restJson;
            }
        }else {
            restJson = new RestJson(false, "此账号未被注册", 2);
            return restJson;
        }

    }
    //判断验证码是否正确,手机号验证码进行登录
    @RequestMapping("/yzm/else")
    @ResponseBody
    public RestJson shoujihaoyanzhegnma(String yanzhengma, @ModelAttribute("Numeric") String numeric,
                                        @ModelAttribute("UTel") String uTel, ModelMap map,@ModelAttribute("uId") Integer uId) {
        System.out.println("yanzhengma = " + yanzhengma);
        System.out.println("numeric = " + numeric);
        System.out.println("uTel = " + uTel);
        System.out.println("uId = " + uId);

        TUser user=new TUser();
        user.setuId(uId);

        if (numeric.equals(yanzhengma)) {
            restJson = new RestJson(true, "验证码正确", user);
            // return "0";//代表正确
        } else {
            restJson = new RestJson(false, "验证码错误", 1);
        }
        //return "1";//代表错误
        return restJson;
    }

}
